import router from './router'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken ,getCustomerId} from '@/utils/auth'
import { isHttp } from '@/utils/validate'
import { isRelogin } from '@/utils/request'
import useUserStore from '@/store/modules/user'
import useSettingsStore from '@/store/modules/settings'
import usePermissionStore from '@/store/modules/permission'
import useCustomerStore from "./store/modules/customer";

NProgress.configure({ showSpinner: false });

const whiteList = ['/login', '/register','/','/userLogin','/userRegister'];

router.beforeEach((to, from, next) => {
  console.log(to.path+"       "  +to.fullPath+"   "+from.fullPath)
  //NProgress是一个用于在网页中显示页面加载进度条的 JavaScript 库
  NProgress.start()
  console.log(localStorage.getItem("id"))
  if (getToken()) {
    //设置网页标题
    to.meta.title && useSettingsStore().setTitle(to.meta.title)
    /* has token*/
    //管理员
    if (to.path === '/login') {
      console.log("to.path = /login")
      next({ path: '/toindex' })
      NProgress.done()
    } else if (whiteList.indexOf(to.path) !== -1) {
      console.log("在白名单里")
      next()
    } else if(getCustomerId()){
      //顾客路由
      console.log("顾客权限")
      next()
    }
    else{
      console.log(useCustomerStore().id)
      console.log("用户权限")
        console.log(useUserStore().id)
      //用户权限
      if (useUserStore().roles.length === 0) {
        isRelogin.show = true
        // 判断当前用户是否已拉取完user_info信息
        useUserStore().getInfo().then(() => {
          isRelogin.show = false
          usePermissionStore().generateRoutes().then(accessRoutes => {
            // 根据roles权限生成可访问的路由表
            accessRoutes.forEach(route => {
              if (!isHttp(route.path)) {
                router.addRoute(route) // 动态添加可访问路由表
              }
            })
            next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
          })
        }).catch(err => {
          useUserStore().logOut().then(() => {
            ElMessage.error(err)
            next({ path: '/' })
          })
        })
      } else {
        next()
      }
    }
  } else {
    // 没有token
    console.log("没有token")
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      console.log("在免登录白名单，直接进入")
      next()
    }
    else {
      console.log("不在白名单")
      //todo 提示登录
      alert("登录")
      next(`/?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
